package validate

import (
	"context"
	"gitee.com/bobo-rs/innovideo-services/enums"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/util/gvalid"
)

// RuleRegisterVideo 视频注册规则
func RuleRegisterVideo() {
	gvalid.RegisterRuleByMap(map[string]gvalid.RuleFunc{
		`video-exists-id`:      RuleVideoExistsById,
		`video-valid-id`:       RuleValidVideoById,
		`video-cate-delete`:    RuleVideoCategoryDelete,
		`video-delete`:         RuleVideoDelete,
		`video-cate-exists-id`: RuleVideoCategoryExistsById,
		`episodes-exists-id`:   RuleEpisodesExistsById,
		`resolution-exists-id`: RuleResolutionExistsById,
		`personal-exists-id`:   RulePersonalExistsById,
		`is-buy-episodes`:      RuleIsBuyEpisodesIdSet, // 检测选中的剧集是否已经购买
		`video-buy-exists-id`:  RuleBuyExistsById,
		`video-bill-exists-id`: RuleVideoBillExistsById,
		`is-top-video-cate`:    RuleIsTopVideoCategory, // 是否顶级视频类目
	})
}

// RuleVideoExistsById 通过视频ID验证视频是否存在
func RuleVideoExistsById(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}

	// 验证是否是否存在
	if b, _ := service.Video().VideoModel().ExistsPri(ctx, in.Value.Uint()); !b {
		return exception.New(`视频不存在`)
	}
	return nil
}

// RuleValidVideoById 验证有效视频信息
func RuleValidVideoById(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}

	var item model.VideoStatusAttrItem
	if err := service.Video().VideoModel().DetailPri(ctx, in.Value.Uint(), &item); err != nil {
		return exception.New(`视频不存在`)
	}

	// 状态
	if item.Status != uint(enums.VideoStatusSuccess) {
		return exception.New(`视频未上架`)
	}

	// 是否发布
	if item.IsRelease == uint(enums.VideoReleaseNot) {
		return exception.New(`视频未发布`)
	}
	return nil
}

// RuleVideoDelete 视频删除验证
func RuleVideoDelete(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}

	var item model.VideoStatusAttrItem
	if err := service.Video().VideoModel().DetailPri(ctx, in.Value.Uint(), &item); err != nil {
		return exception.New(`视频不存在`)
	}

	// 视频状态
	if item.Status != uint(enums.VideoStatusDel) {
		return exception.New(`请先移除到废弃仓库`)
	}
	return nil
}

// RulePersonalExistsById 通过视频常用人员ID检测参演信息是否存在
func RulePersonalExistsById(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}
	if b, _ := service.Video().PersonalModel().ExistsPri(ctx, in.Value.Uint()); !b {
		return exception.New(`参演人员信息不存在`)
	}
	return nil
}
